/**
 * Software License, Version 1.0
 * 
 * Copyright 2008 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgment:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgment may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or Granules, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called Granules, 
 * nor may Indiana University or Community Grids Lab or Granules appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 * WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 * NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 * GENERATED USING SOFTWARE.
 */
package cgl.granules.scheduler;

import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import cgl.granules.exception.CommunicationsException;
import cgl.narada.event.NBEvent;
import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.matching.Profile;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.ClientService;
import cgl.narada.service.client.EventConsumer;
import cgl.narada.service.client.EventProducer;
import cgl.narada.service.client.NBEventListener;
import cgl.narada.service.client.SessionService;

/**
 * A streaming service class which abstracts minimal operations needed for
 * communications.
 * 
 * @author Shrideep Pallickara
 * 
 */
public class StreamingService {

	private static final StreamingService instance = new StreamingService();
	private CountDownLatch initLatch = new CountDownLatch(1);;
	private ClientService clientService;
	private static boolean initialized = false;
	private boolean debug = false;
	// private EventConsumer ssEventConsumer;
	private EventProducer ssEventProducer;

	private StreamingService() {
	}

	/**
	 * Get an instance of the StreamingService
	 * 
	 * @return The singleton instance of the StreamingService
	 */
	public static StreamingService getInstance() {
		return instance;
	}

	/**
	 * Initialize the streaming service based on the specified parameters
	 * 
	 * @param configurationFile
	 *            Used to specify configuration of various services
	 * @param entityId
	 *            The identifier associated with this entity/resource
	 * @param props
	 *            Properties for initializing communications with the broker
	 * @param commType
	 *            The communication type to be used
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public synchronized void initialize(String configurationFile, int entityId,
			Properties props, String commType) throws CommunicationsException {
		String errorReport = null;
		if (initialized) {
			errorReport = "The StreamingService has already been initialized";
			return;
		}

		try {
			if (configurationFile != null) {
				SessionService
						.setServiceConfigurationLocation(configurationFile);
			}
			clientService = SessionService.getClientService(entityId);
			clientService.initializeBrokerCommunications(props, commType);

			if (debug) {
				System.out.println("StreamingService: Initialized (" + entityId
						+ ")");
			}
			ssEventProducer = clientService.createEventProducer();

			initialized = true;
			initLatch.countDown();
		} catch (ServiceException se) {
			errorReport = se.toString();
			throwCommunicationsException(errorReport);
		}
	}

	/**
	 * Checks to see if the streaming service has been initialized.
	 * 
	 * @return <code>true</code> if it is, and <code>true</code> otherwise.
	 */
	public boolean isInitialized() {
		return initialized;
	}

	/**
	 * Create a stream producer
	 * 
	 * @return The stream producer
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public EventProducer createProducer() throws CommunicationsException {

		String errorReport = "Creation of EventProducer failed: ";
		EventProducer eventProducer = null;
		try {
			initLatch.await();
			eventProducer = clientService.createEventProducer();

		} catch (InterruptedException ie) {
			errorReport += ie.getMessage();
			throwCommunicationsException(errorReport);
		} catch (ServiceException se) {
			errorReport += se.toString();
			throwCommunicationsException(errorReport);
		}
		return eventProducer;
	}

	/**
	 * Create an event consumer
	 * 
	 * @param listener
	 *            The listener who would be notified when streams are available
	 * @return An event consumer
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public EventConsumer createConsumer(NBEventListener listener)
			throws CommunicationsException {

		String errorReport = "Creation of EventConsumer failed: ";
		EventConsumer eventConsumer = null;
		try {
			initLatch.await();
			eventConsumer = clientService.createEventConsumer(listener);

		} catch (InterruptedException ie) {
			errorReport += ie.getMessage();
			throwCommunicationsException(errorReport);
		} catch (ServiceException se) {
			errorReport += se.toString();
			throwCommunicationsException(errorReport);
		}
		return eventConsumer;

	}

	/**
	 * Create a profile based on the synopsisTypeString and the synopsis
	 * 
	 * @param streamSynopsis
	 *            The synopsis of the Stream
	 * @param synopsisType
	 *            The synopsis type of the stream in question
	 * @return A profile based on the specified parameters
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public Profile createProfile(String streamSynopsis, int synopsisType)
			throws CommunicationsException {

		String errorReport = "Creation of Profile failed: ";
		Profile profile = null;
		try {
			initLatch.await();
			profile = clientService.createProfile(synopsisType, streamSynopsis);
		} catch (InterruptedException ie) {
			errorReport += ie.getMessage();
			throwCommunicationsException(errorReport);
		} catch (ServiceException se) {
			errorReport += se.toString();
			throwCommunicationsException(errorReport);
		}
		return profile;
	}

	/**
	 * Writes a byte[] payload onto the specified stream
	 * 
	 * @param streamSynopsis
	 *            The synopsis of the Stream
	 * 
	 * @param payload
	 *            The payload for the stream fragment
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public void writeToStream(String streamSynopsis, byte[] payload)
			throws CommunicationsException {

		int synopsisType = TemplateProfileAndSynopsisTypes.STRING;
		writeToStream(streamSynopsis, synopsisType, payload);
	}

	/**
	 * Writes a byte[] payload onto the specified stream
	 * 
	 * @param streamSynopsis
	 *            The synopsis of the Stream
	 * @param synopsisType
	 *            The synopsis type of the stream in question
	 * @param payload
	 *            The payload for the stream fragment
	 * @throws CommunicationsException
	 *             If there are communication problems when performing the
	 *             operation.
	 */
	public void writeToStream(String streamSynopsis, int synopsisType,
			byte[] payload) throws CommunicationsException {

		try {
			initLatch.await();
			NBEvent nbEvent = ssEventProducer.generateEvent(synopsisType,
					streamSynopsis, payload);
			ssEventProducer.publishEvent(nbEvent);
		} catch (InterruptedException ie) {
			throwCommunicationsException(ie.getMessage());
		} catch (ServiceException se) {
			throwCommunicationsException(se.getMessage());
		}
	}

	private void throwCommunicationsException(String errorReport)
			throws CommunicationsException {
		throw new CommunicationsException(errorReport);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
